/**
 * Created by YMP on 2019/10/7.
 */

import Taro from '@tarojs/taro'
/**
 * 提示与加载工具类
 */
export default class Tips {
  constructor() {
    this.isLoading = false
  }

  /**
   * 弹出成功提示框
   */
  static success(title, duration = 600) {
    setTimeout(() => {
      Taro.showToast({
        title: title,
        icon: 'success',
        mask: true,
        duration: duration
      })
    }, 300)
    if (duration > 0) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve()
        }, duration)
      })
    }
  }

  /**
   * 弹出confirm确认窗口
   */
  static confirm(title = '提示', text) {
    return new Promise((resolve, reject) => {
      Taro.showModal({
        title: title,
        content: text,
        showCancel: true,
        success: res => {
          if (res.confirm) {
            resolve()
          } else if (res.cancel) {
            reject(res.cancel)
          }
        },
        fail: res => {
          reject(res)
        }
      })
    })
  }

  /**
   * 文字提示框
   * @param title
   * @param onHide
   * @param icon
   */
  static toast(title, time = 1200, image = '', icon = 'none') {
    return new Promise(resolve => {
      setTimeout(() => {
        Taro.showToast({
          title: title,
          image: image,
          icon: icon,
          mask: true,
          duration: time
        })
      }, 300)

      // 隐藏结束回调
      setTimeout(() => {
        resolve()
      }, time)
    })
  }

  /**
   * 显示操作菜单
   * @param itemList
   * @param itemColor
   * @returns {Promise<any>}
   */
  static showActionSheet(itemList = [], itemColor = '#000000') {
    return new Promise((resolve, reject) => {
      Taro.showActionSheet({
        itemList: itemList,
        itemColor: itemColor,
        success: res => {
          resolve(res.tapIndex)
        },
        fail: res => {
          reject(res.errMsg)
        }
      })
    })
  }
  /**
   * 警告框
   */
  static alert(title, time = 1200) {
    Taro.showToast({
      title: title,
      icon: 'none',
      mask: true,
      duration: time
    })
  }

  /**
   * 错误框
   */

  static error(title, time = 1200) {
    return new Promise(resolve => {
      Taro.showToast({
        title: title,
        icon: 'none',
        mask: true,
        duration: time
      })
      // 隐藏结束回调
      setTimeout(() => {
        resolve()
      }, time)
    })
  }

  /**
   * 弹出加载提示
   */
  static loading(title = '加载中') {
    if (Tips.isLoading) {
      return
    }
    Tips.isLoading = true
    Taro.showLoading({
      title: title,
      mask: true
    })
  }

  /**
   * 加载完毕
   */
  static loaded() {
    return new Promise(resolve => {
      if (Tips.isLoading) {
        Tips.isLoading = false
        Taro.hideLoading()
        resolve()
      }
    })
  }
}

/**
 * 静态变量，是否加载中
 */
Tips.isLoading = false
